<template>
  <div>
    <p>脚本名称：{{ scriptData?.name || '' }}</p>
    <div>
      <p>标签：
        <el-radio-group v-model="checkedCities">
          <el-radio :value="city.id" v-for="city in cities" :key="city.id">{{ city.name }}</el-radio>
        </el-radio-group>
      </p>
    </div>
    <div class="button">
      <el-button @click="onReset">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { tagList,scriptUpdate } from '@/api/scriptLibrary'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  scriptData: any
}>()
const radioProps = { value: 'id', label: 'name' }

const emit = defineEmits<{
  update: []
  close: []
}>()

const checkedCities = ref<string>('')
const cities = ref<any[]>([])


// 获取标签列表
const getList = async () => {
  try {
    const res = await tagList()
    if (res.data.code === 200 && res.data.data) {
      cities.value = res.data.data
      // 初始化已选标签
      initSelectedTags()
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 初始化已选标签
    const initSelectedTags = () => {
      console.log('[ props.scriptData ] >', props.scriptData)
      if (props.scriptData && props.scriptData.tag ) {
        // 单选只取第一个标签的id
        checkedCities.value = props.scriptData.tag.id
      }
    }

// 监听脚本数据变化
watch(() => props.scriptData, () => {
  if (cities.value) {
    initSelectedTags()
  }
}, { deep: true })

// 提交表单
const onSubmit = async() => {
  try {
    if (!props.scriptData || !props.scriptData.id) {
      ElMessage.error('脚本数据不完整，无法更新')
      return
    }
    
    const data = {
      id: props.scriptData.id,
      tag: checkedCities.value ? checkedCities.value : ''
    }
    
    console.log('提交标签更新:', data)
    const res = await scriptUpdate(data)
    
    if (res.data.code === 200) {
      ElMessage.success('标签更新成功')
      emit('update')
      emit('close')
    } else {
      ElMessage.error(res.data.msg || '标签更新失败')
    }
  } catch (error) {
    console.error('标签更新失败:', error)
    ElMessage.error('标签更新失败')
  }
}

// 取消操作
const onReset = () => {
  emit('close')
}

onMounted(() => {
  getList()
})
</script>
<style lang="scss" scoped>
.button {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>